package cn.edu.ujn.lab3.web.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.edu.ujn.lab3.dao.BaseDict;
import cn.edu.ujn.lab3.dao.User;
import cn.edu.ujn.lab3.service.BaseDictService;
import cn.edu.ujn.lab3.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private BaseDictService baseDictService;
	// 客户来源
//		@Value("${customer.from.type}")
	private String FROM_TYPE = "002";
	// 客户所属行业
//		@Value("${customer.industry.type}")
	private String INDUSTRY_TYPE = "001";
	// 客户级别
//		@Value("${customer.level.type}")
	private String LEVEL_TYPE = "006";

	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	public String login(String usercode, String password, Model model, HttpSession session) {
		// 客户来源
		List<BaseDict> fromType = baseDictService.findBaseDictByTypeCode("002");
		// 客户所属行业
		List<BaseDict> industryType = baseDictService.findBaseDictByTypeCode("001");
		// 客户级别
		List<BaseDict> levelType = baseDictService.findBaseDictByTypeCode("006");
		// 添加参数
		model.addAttribute("fromType", fromType);
		model.addAttribute("industryType", industryType);
		model.addAttribute("levelType", levelType);
		// 通过账号和密码查询用户
		User user = userService.findUser(usercode, password);
		if (user != null) {
			// 将用户对象添加到Session
			session.setAttribute("USER_SESSION", user);
			// 跳转到主页面
			return "customer";
//			return "redirect:customer";
		}
		model.addAttribute("msg", "账号或密码错误，请重新输入！");
		// 返回到登录页面
		return "login";
	}

	/**
	 * 退出登录
	 */
	@RequestMapping(value = "/logout.action")
	public String logout(HttpSession session) {
		// 清除Session
		session.invalidate();
		// 重定向到登录页面的跳转方法
		return "redirect:login.action";
	}

	/**
	 * 向用户登陆页面跳转
	 */
	@RequestMapping(value = "/login.action", method = RequestMethod.GET)
	public String toLogin() {
		return "login";
	}

	/**
	 * 模拟其他类中跳转到客户管理页面的方法
	 */
	@RequestMapping(value = "/toCustomer.action")
	public String toCustomer() {
		return "customer";
	}
}
